package com.swk.login;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 使用session完成登录
 */
@WebServlet("/SessionLogin")
public class SessionLoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public SessionLoginServlet() {
        super();
    }

	/**
	 * 登出入口
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// 有参数false，只做检索，如果没有session，返回为空，不会创建新的session
		HttpSession session = request.getSession(false);
		if (session != null) {
			session.removeAttribute("userBean");// 移除session标记
		}
		response.sendRedirect("/webDetail/index.jsp");
	}

	/**
	 * 登录入口
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		
		//获取请求参数
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		//参数校验
		if (username == null || username.trim().length() == 0) {
			response.getWriter().write("账号不能为空！");
			return;
		}
		if (password == null || password.trim().length() == 0) {
			response.getWriter().write("密码不能为空！");
			return;
		}
		
		//数据库验证账号
		List<UserBean> list = DB.getAll();
		for (UserBean userBean : list) {
			if(userBean.getUsername().equals(username) && userBean.getPassword().equals(password)){
				//验证成功
				HttpSession session = request.getSession(true);
				session.setAttribute("userBean", userBean);
				Cookie cookie = new Cookie("JSESSIONID", session.getId());//重新存JSESSIONID
				cookie.setMaxAge(30 * 60);//延长有效期，30分钟
				response.addCookie(cookie);
				response.sendRedirect("/webDetail/index.jsp");
				return;
			}
		}
		
		response.getWriter().write("账号或密码错误！");
	}//post

}//class

/**
 * 模拟数据库用户信息表
 */
class DB {
	private static List<UserBean> list = new ArrayList<UserBean>();
	static {
		list.add(new UserBean("aaa", "123"));
		list.add(new UserBean("bbb", "123"));
		list.add(new UserBean("ddd", "123"));
		list.add(new UserBean("ccc", "123"));
		list.add(new UserBean("ttt", "123"));
	}

	public static List<UserBean> getAll() {
		return list;
	}
}

